package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.FileUploadVo;
import com.ybkj.daijia.common.MediaUtil;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.RentApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.model.DredgeVehicle;
import com.ybkj.daijia.server.model.RentShop;
import com.ybkj.daijia.server.service.RentShopService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * @author Blazk.
 */
@RestController
@RequestMapping(value = "rentshop")
public class RentShopController {

    @Autowired
    private RentApi rentApi;
    @Autowired
    private RentShopService rentShopService;
    @Value("${file.upload.url}")
    private String fileUploadUrl;
    @Autowired
    private SettingUtils settingUtils;

    @RequestMapping(value = "rentshoplist", method = RequestMethod.GET)
    public ModelAndView rentshoplist() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentshop")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("rentshop/rentshoplist");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "insertrentshop", method = RequestMethod.GET)
    public ModelAndView insertrentshop() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentshop")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("fileUploadUrl", fileUploadUrl);
            mv.setViewName("rentshop/insertrentshop");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "updaterentshop", method = RequestMethod.GET)
    public ModelAndView updaterentshop(@RequestParam("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentshop")) {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("id", id);
            modelAndView.addObject("fileUploadUrl", fileUploadUrl);
            modelAndView.setViewName("rentshop/updaterentshop");
            return modelAndView;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "insertRentshop", method = RequestMethod.POST)
    public Map<String, Object> insertRentshop(
        @RequestParam("companyId") Long companyId,
        @RequestParam("companyName") String companyName,
        @RequestParam("shopName") String shopName,
        @RequestParam("address") String address,
        @RequestParam("lat") Double lat,
        @RequestParam("lng") Double lng,
        @RequestParam("serviceRange") Double serviceRange,
        @RequestParam("contacts") String contacts,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "telephone") String telephone,
        @RequestParam(required = false, value = "email") String email,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "image") String image,
        @RequestParam(required = false, value = "city") String city,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("companyId", String.valueOf(companyId));
        kv.add("lat", String.valueOf(lat));
        kv.add("lng", String.valueOf(lng));
        kv.add("serviceRange", String.valueOf(serviceRange));
        kv.add("companyName", companyName);
        kv.add("shopName", shopName);
        kv.add("address", address);
        kv.add("contacts", contacts);
        kv.add("phone", phone);
        kv.add("telephone", telephone);
        kv.add("email", email);
        kv.add("memo", memo);
        kv.add("image", image);
        kv.add("city", city);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_RENTSHOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "创建成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "deleteRentshop", method = RequestMethod.POST)
    public Map<String, Object> deleteRentshop(@RequestParam("id") Long id,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.DELETE_RENTSHOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "删除成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateRentshop", method = RequestMethod.POST)
    public Map<String, Object> updateRentshop(
        @RequestParam("id") Long id,
        @RequestParam(required = false, value = "address") String address,
        @RequestParam(required = false, value = "shopName") String shopName,
        @RequestParam(required = false, value = "companyName") String companyName,
        @RequestParam(required = false, value = "contacts") String contacts,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "telephone") String telephone,
        @RequestParam(required = false, value = "email") String email,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "image") String image,
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "serviceRange") Double serviceRange,
        @RequestParam(required = false, value = "lat") Double lat,
        @RequestParam(required = false, value = "lng") Double lng,
        @RequestParam(required = false, value = "city") String city,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        if (StringUtils.isNotBlank(address)) {
            kv.add("address", address);
        }
        if (StringUtils.isNotBlank(shopName)) {
            kv.add("shopName", shopName);
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.add("companyName", companyName);
        }
        if (StringUtils.isNotBlank(contacts)) {
            kv.add("contacts", contacts);
        }
        if (StringUtils.isNotBlank(phone)) {
            kv.add("phone", phone);
        }
        if (StringUtils.isNotBlank(telephone)) {
            kv.add("telephone", telephone);
        }
        if (StringUtils.isNotBlank(city)) {
            kv.add("city", city);
        }
        if (StringUtils.isNotBlank(email)) {
            kv.add("email", email);
        }
        if (StringUtils.isNotBlank(memo)) {
            kv.add("memo", memo);
        }
        if (StringUtils.isNotBlank(image)) {
            kv.add("image", image);
        }
        if (companyId != null) {
            kv.add("companyId", String.valueOf(companyId));
        }
        if (serviceRange != null) {
            kv.add("serviceRange", String.valueOf(serviceRange));
        }
        if (lat != null) {
            kv.add("lat", String.valueOf(lat));
        }
        if (lng != null) {
            kv.add("lng", String.valueOf(lng));
        }

        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_RENTSHOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "selectRentshop", method = RequestMethod.GET)
    public RentShop selectRentshop(@RequestParam("id") Long id,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_RENTSHOP)
            .append("?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject dataList = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().create();
                RentShop rentShop = gson.fromJson(dataList.toString(),
                    RentShop.class);
                return rentShop;
            }
        }
        return null;
    }

    @RequestMapping(value = "selectRentshopByShopName", method = RequestMethod.GET)
    public Page<RentShop> selectRentshopByShopName(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "shopName") String shopName,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_RENTSHOP_BY_SHOP_NAME)
            .append("?appkey={appkey}");
        if (StringUtils.isNotBlank(shopName)) {
            kv.put("shopName", shopName);
            builder.append("&shopName={shopName}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        // {"code":0,"message":"成功","dataList":[{"id":1,"created":null,"categoryTop":1,"categoryTopName":"test1"}],"total":1}
        List<RentShop> rentShop = new ArrayList<RentShop>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject dataList = jo.getJSONObject("data");
                total = dataList.getLong("total");
                JSONArray jsonArray = dataList.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                rentShop = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<RentShop>>() {
                    }.getType());

            }
        }
        return new PageImpl<RentShop>(rentShop, pageable, total);
    }

    // Excel导出门市信息 调用selectByShopName 设置appkey 其他不用管
    // 导出(未写完)
    @RequestMapping(value = "exportRentShop", method = RequestMethod.GET)
    public void exportOrder(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = false, value = "shopName") String shopName,
        /*
         * @RequestParam(required = false, value = "address") String
         * address,
         *
         * @RequestParam(required = false, value = "lat") Double lat,
         *
         * @RequestParam(required = false, value = "lng") Double lng,
         *
         * @RequestParam(required = false, value = "contacts") String
         * contacts,
         *
         * @RequestParam(required = false, value = "phone") String phone,
         *
         * @RequestParam(required = false, value = "telephone") String
         * telephone,
         *
         * @RequestParam(required = false, value = "email") String email,
         *
         * @RequestParam(required = false, value = "serviceRange;") Double
         * serviceRange,
         *
         * @RequestParam(required = false, value = "memo") String memo,
         *
         * @RequestParam(required = false, value = "image") String image,
         */
        HttpServletRequest req, HttpServletResponse response)
        throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");

        List<List<String>> rowlist = new ArrayList<List<String>>();
        String[] head = new String[10];
        head[0] = ("门店名称");
        head[1] = ("门店地址");
        head[2] = ("门店地址纬度");
        head[3] = ("门店地址经度");
        head[4] = ("门店联系人");
        head[5] = ("门店联系电话");
        head[6] = ("门店联系座机");
        head[7] = ("门店联系邮件");
        head[8] = ("门店服务范围");
        head[9] = ("门店备注");

        List<RentShop> rentShopList = rentShopService.exportRentShop(companyId,
            shopName);

        for (RentShop rentshop : rentShopList) {
            List<String> dataList = new ArrayList<String>();
            dataList.add(rentshop.getShopName());
            dataList.add(rentshop.getAddress());
            dataList.add(String.valueOf(rentshop.getLat()));
            dataList.add(String.valueOf(rentshop.getLng()));
            dataList.add(rentshop.getContacts());
            dataList.add(rentshop.getPhone());
            dataList.add(rentshop.getTelephone());
            dataList.add(rentshop.getEmail());
            dataList.add(String.valueOf(rentshop.getServiceRange()));
            dataList.add(rentshop.getMemo());
            rowlist.add(dataList);

        }

        ExcelUtil.export(req, response, head, rowlist);
    }

    /**
     * 上传租车门店照片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadRentshopImage")
    public @ResponseBody
    FileUploadVo uploadRentshopImage(
        @RequestParam("pic1") MultipartFile imgFile,
        @RequestParam("type") String folder, HttpServletRequest req)
        throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMMdd");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName.substring(moduleName.lastIndexOf(".") + 1,
                moduleName.length());
            String filestr = "upload/"
                + folder
                + "/"
                + monthstr
                + "/"
                + now.getTime()
                + moduleName.substring(moduleName.lastIndexOf("."),
                moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf("."))
                + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); // 上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(300, 200)
                        .toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String basePath = req.getScheme() + "://" + req.getServerName()
                    + ":" + req.getServerPort() + req.getContextPath();// +request.getRequestURI();
                vo.setUrl(basePath + "/" + filestr);
                vo.setMinurl(basePath + "/" + minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    // @RequestMapping(method=RequestMethod.POST,value="uploadRentshopImage")
    // public void uploadRentshopImage(
    // @RequestParam("pic1") MultipartFile imgFile,
    // @RequestParam("type") String folder,
    // HttpServletResponse resp,HttpServletRequest req) throws IOException{
    //
    // resp.setHeader("Access-Control-Allow-Origin", "*");
    // FileUploadVo vo=new FileUploadVo();
    //
    // String moduleName = imgFile.getOriginalFilename();
    //
    // if(MediaUtil.isPicture(moduleName, "")){
    // String bathPath = getBasePath(req);
    // SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMMdd");
    // Date now=new Date();
    // String monthstr=monthFormat.format(now);
    // String type =
    // moduleName.substring(moduleName.lastIndexOf(".")+1,moduleName.length());
    // String
    // filestr="upload/"+folder+"/"+monthstr+"/"+now.getTime()+moduleName.substring(moduleName.lastIndexOf("."),moduleName.length());
    // String minImg=filestr.substring(0,filestr.lastIndexOf("."))+"min."+type;
    // File f=new File(bathPath,filestr);
    //
    // if (!f.getParentFile().exists()) {
    // f.getParentFile().mkdirs();
    // }
    //
    // try {
    // File tempDest = new
    // File(System.getProperty("java.io.tmpdir"),"upload_"+String.valueOf(System.nanoTime())+".tmp");
    // imgFile.transferTo(tempDest); //上传到临时文件中
    // FileUtils.copyFile(tempDest, f);
    // tempDest.delete();
    // try{
    // Thumbnails.of(f).size(300, 200).toFile(new File(bathPath,minImg));
    // }catch (Exception e){
    // e.printStackTrace();
    // }
    //
    // String basePath = req.getScheme()+"://"+
    // req.getServerName()+":"+req.getServerPort()+req.getContextPath();//+request.getRequestURI();
    // vo.setUrl(basePath+"/"+filestr);
    // vo.setMinurl(basePath+"/"+minImg);
    // vo.setSuccess(true);
    // resp.setContentType("text/html;charset=UTF-8");
    // Writer writer = resp.getWriter();
    //
    // ObjectMapper mapper = new ObjectMapper();
    // mapper.writeValue(writer, vo);
    //
    // } catch (Exception e) {
    // vo.setMsg(e.getMessage());
    // vo.setSuccess(false);
    // resp.setContentType("text/html;charset=UTF-8");
    // Writer writer = resp.getWriter();
    // ObjectMapper mapper = new ObjectMapper();
    // mapper.writeValue(writer, vo);
    // }
    // }
    // else{
    // vo.setMsg("只能上传图片");
    // vo.setSuccess(false);
    // resp.setContentType("text/html;charset=UTF-8");
    // Writer writer = resp.getWriter();
    // ObjectMapper mapper = new ObjectMapper();
    // mapper.writeValue(writer, vo);
    // }
    //
    // }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(),
                "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

    @RequestMapping(value = "dredgeShopVehicle", method = RequestMethod.POST)
    public Map<String, Object> dredgeShopVehicle(
        @RequestParam("shopId") Long shopId,
        @RequestParam("vehicleId") Long vehicleId, HttpServletRequest req,
        HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("shopId", String.valueOf(shopId));
        kv.add("vehicleId", String.valueOf(vehicleId));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.DREDGE_SHOP_VEHICLE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "开通车系成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "closeShopVehicle", method = RequestMethod.POST)
    public Map<String, Object> closeShopVehicle(@RequestParam("id") Long id,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.CLOSE_SHOP_VEHICLE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "关闭车系成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "findShopVehicleByVehicleId", method = RequestMethod.GET)
    public Page<DredgeVehicle> findShopVehicleByVehicleId(
        @RequestParam(required = false, value = "vehicleId") Long vehicleId,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_SHOP_BY_VEHICLEID)
            .append("?appkey={appkey}");
        if (vehicleId != null) {
            kv.put("vehicleId", String.valueOf(vehicleId));
            builder.append("&vehicleId={vehicleId}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<DredgeVehicle> dredgeVehicle = new ArrayList<DredgeVehicle>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject dataList = jo.getJSONObject("data");
                total = dataList.getLong("total");
                JSONArray jsonArray = dataList.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                dredgeVehicle = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<DredgeVehicle>>() {
                    }.getType());
            }
        }
        return new PageImpl<DredgeVehicle>(dredgeVehicle, pageable, total);
    }

    @RequestMapping(value = "selectRentshops", method = RequestMethod.GET)
    public Page<RentShop> selectRentshops(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam("vehicleId") Long vehicleId,
        @RequestParam(required = false, value = "shopName") String shopName,
        HttpServletRequest req, HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_RENTSHOP_BY_SHOP_NAME)
            .append("?appkey={appkey}");
        if (StringUtils.isNotBlank(shopName)) {
            kv.put("shopName", shopName);
            builder.append("&shopName={shopName}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        // {"code":0,"message":"成功","dataList":[{"id":1,"created":null,"categoryTop":1,"categoryTopName":"test1"}],"total":1}
        List<RentShop> rentShop = new ArrayList<RentShop>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject dataList = jo.getJSONObject("data");
                total = dataList.getLong("total");
                JSONArray jsonArray = dataList.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                rentShop = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<RentShop>>() {
                    }.getType());

            }
        }
        List<DredgeVehicle> dredgeVehicles = findShopVehicleByVehicleId(
            vehicleId, null, null, req, resp).getContent();

        List<RentShop> removable = new LinkedList<RentShop>();

        if (null != dredgeVehicles && null != rentShop) {
            for (RentShop shop : rentShop) {
                for (DredgeVehicle vehicle : dredgeVehicles) {
                    if (shop.getId().equals(vehicle.getShopId())) {
                        removable.add(shop);
                        total--;
                    }
                }
            }
        }
        rentShop.removeAll(removable);

        return new PageImpl<RentShop>(rentShop, pageable, total);
    }
}
